<?php
	include_once($config[webroot]."/includes/page_utf_class.php");
	include_once($config[webroot]."/module/quanfan/includes/plugin_quanfan_class.php");
	$quanfan = new Quanfan();
	
	
	if($_GET['operation']=="add" or $_GET['operation']=="edit")
	{
		if($_POST['act'])
		{	
			unset($_GET['operation']);
			unset($_GET['s']);
			unset($_GET['m']);
			$_POST['stime'].=(' '.$_POST['startHour'].':00:00');
			$_POST['etime'].=(' '.$_POST['endHour'].':59:59');
			//添加
			if($_POST["act"]=='save')
			{
				$sql="insert into ".QUANFAN." (`pid`,
				`hp_title`,
				`pic`,
				`start_time`,
				`end_time`,
				`low_amount`,
				`virtual_amount`,
				`limit_amount`,
				`status`,
				`stock_shop`,
				`price`,
				`market_price`,
				`create_user`
				) values (
				'$_POST[pid]',
				'$_POST[hp_title]',
				'$_POST[pic]',
				'$_POST[stime]',
				'$_POST[etime]',
				'$_POST[low_amount]',
				'$_POST[virtual_amount]',
				'$_POST[limit_amount]',
				'$_POST[status]',
				'{$_POST['stock_shop'][0]}',
				'{$_POST['hp_price'][0]}',
				'{$_POST['hp_market_price'][0]}',
				'{$_SESSION['ADMIN_USER']}'
				)";
				$db->query($sql);
				$hp_id =$db->lastid();
				
				foreach ($_POST[skuid] as $key=>$item){
				    if ($_POST['sku_status'][$key]){
				        $status = $_POST['status'];
				    }else{
				        $status =-1;
				    }
				    $skuData[]="('{$hp_id}','{$item}','{$_POST['hp_price'][$key]}','{$_POST['hp_market_price'][$key]}','{$_POST['hp_stock'][$key]}','{$status}','{$_SESSION['ADMIN_USER']}')";
				}
				$sql="insert into ".QUANFANSKU." (
				`hp_id`,
				`sku_id`,
				`hp_price`,
				`hp_market_price`,
				`hp_stock`,
				`status`,
				`create_user`
				) values ".implode(',', $skuData);
				$db->query($sql);
			}
			//修改
			if($_POST["act"]=='edit' and is_numeric($_POST['id']))
			{
			    $sql="select pid from ".QUANFAN." where id='{$_POST['id']}'";
			    $db->query($sql);
			    if($_POST['pid'] ==$db->fetchField('pid')){
			        $isChangePro=false;
			    }else{
			        $isChangePro =true;
			    }
				$sql=" update ".QUANFAN." set 
				    
				`pid` = '$_POST[pid]',
				`hp_title` ='$_POST[hp_title]',
				`pic`='$_POST[pic]',
				`start_time`='$_POST[stime]',
				`end_time`='$_POST[etime]',
				`low_amount`='$_POST[low_amount]',
				`virtual_amount`='$_POST[virtual_amount]',
				`limit_amount`='$_POST[limit_amount]',
				`status`='$_POST[status]',
				`stock_shop`='{$_POST['stock_shop'][0]}',
				`price`='{$_POST['hp_price'][0]}',
				`market_price`='{$_POST['hp_market_price'][0]}'
				 WHERE id='{$_POST['id']}'
				    ";
				$db->query($sql);
				if ($isChangePro){
					$sql="update ".QUANFANSKU." SET status=-9 where hp_id = '{$_POST['id']}'";
					$db->query($sql);
					foreach ($_POST[skuid] as $key=>$item){
					    if ($_POST['sku_status'][$key]){
					        $status = $_POST['status'];
					    }else{
					        $status =-9;
					    }
					    $skuData[]="('{$_POST['id']}','{$item}','{$_POST['hp_price'][$key]}','{$_POST['hp_market_price'][$key]}','{$_POST['hp_stock'][$key]}','{$status}','{$_SESSION['ADMIN_USER']}')";
					}
				$sql="insert into ".QUANFANSKU." (
				`hp_id`,
				`sku_id`,
				`hp_price`,
				`hp_market_price`,
				`hp_stock`,
				`status`,
				`create_user`
				) values ".implode(',', $skuData);
					$db->query($sql);
				}else{
				    foreach ($_POST[skuid] as $key=>$item){
				        if ($_POST['sku_status'][$key]){
				            $status = $_POST['status'];
				        }else{
				            $status =-9;
				        }
				        
				        $sql="update ".QUANFANSKU." set
				`hp_price`='{$_POST['hp_price'][$key]}',
				`hp_market_price`='{$_POST['hp_market_price'][$key]}',
				`hp_stock`='{$_POST['hp_stock'][$key]}',
				`status`='{$status}'
				 WHERE  hp_id = '{$_POST['id']}' and sku_id={$item} limit 1";
				       $db->query($sql);
				    }
				    
				}
				unset($_GET['editid']);
			}
			$getstr=implode('&',convert($_GET));
			msg("?m=QUANFAN&s=QUANFAN.php$getstr");
		}
		//信息
		if($_GET['editid'] and is_numeric($_GET['editid']))
		{
			$sql="select * from ".QUANFAN." where id='$_GET[editid]'";
			$db->query($sql);
			$de=$db->fetchRow();
		}
		
		$tpl->assign("config",$config);
	}elseif ($_GET['operation']=="getsku" &&$_GET['pid']){
	    $sql="select id,pid,catid,pname,spec, price,dis_price,market_price,pic,stock,stock_shop from ".SETMEAL." where pid='{$_GET['pid']}' and status>0 ";
	    $db->query($sql);
	    $re=$db->getRows();
	    
	    if ($_GET['hp_id']){
	        $sql="select pid from ".QUANFAN." where id='{$_GET['hp_id']}'";
	        $db->query($sql);
	        if($_GET['pid'] ==$db->fetchField('pid')){
	            $isChangePro=false;
	        }else{
	            $isChangePro =true;
	        }
	        if (!$isChangePro){
	           $sql="select * from ".QUANFANSKU." where hp_id='$_GET[hp_id]'";
	           $db->query($sql);
	           foreach ($skuData=$db->getRows() as $item){
	               $skuInfo[$item['sku_id']]=$item;
	           }
	        }
	        
	    }
	    foreach ($re as $key=> $item){
	        $pics=explode(',', $item['pic']);
	        $re[$key]['pic']=$pics[0];
	        if ($_GET['hp_id']&&!$isChangePro){
	            $re[$key]['hp_price']=$skuInfo[$item['id']]['hp_price'];
	            $re[$key]['hp_stock']=$skuInfo[$item['id']]['hp_stock'];
	            $re[$key]['hp_market_price']=$skuInfo[$item['id']]['hp_market_price'];
	            $re[$key]['hp_amount']=$skuInfo[$item['id']]['hp_amount'];
	            $re[$key]['hp_status']=$skuInfo[$item['id']]['status'];
	        }else{
	            $re[$key]['hp_price']=$item['dis_price'];
	            $re[$key]['hp_stock']=$item['stock'];
	            $re[$key]['hp_market_price']=$item['market_price'];
	            $re[$key]['hp_amount']=0;
	            $re[$key]['hp_status']=1;
	        }
	    }
	    echo json_encode($re);
	    exit;
	}
	else
	{
		if($_POST['act']=='op')
		{
			if($_POST['submit']==$lang['del'])
			{
				if(is_array($_POST['chk']))
				{
					$id=implode(",",$_POST['chk']);
					$sql="update ".QUANFAN." SET status=-9 where id in ($id)";
					$db->query($sql);
					$sql="update ".QUANFANSKU." SET status=-9 where hp_id in ($id)";
					$db->query($sql);
				}
			}
			elseif($_POST['displayorder']&&($_POST['submit']==$lang['btn_submit']))
			{
				foreach($_POST['displayorder'] as $key=>$item)
				{
					$db->query("update ".QUANFAN." set displayorder='$item' where id='$key'");		
				}
			}
			elseif(is_array($_POST['chk']))
			{
				foreach($_POST['chk'] as $item)
				{
				    $status_t = 0;
					if($_POST['submit']=='备货中')
					{
						$status_t = 2;
						//取消未支付的订单
						$quanfan->cancelNonPaymentOrder($item);
					}
					elseif($_POST['submit']==$lang['btn_open'])
					{
						$status_t = 1;
					}
					elseif($_POST['submit']==$lang['btn_close'])
					{
						$status_t = 0;
					}
					elseif ($_POST['submit']=="完成")
					{
					    $status_t = 3;
					    //把已支付的订单中的商品放入微仓
					    $quanfan->updateMicroStockAfterSuccess($item);
					}
					$db->query("update ".QUANFAN." set status='{$status_t}' where id='$item'");
					$db->query("update ".QUANFANSKU." SET status='{$status_t}' where status>-1 and hp_id='$item'");
			    }
			}
			msg("?m=QUANFAN&s=QUANFAN.php$getstr");
		}	
		
		$str = "";
		if($_GET['productId']){
		    $str .= " and pid={$_GET['productId']} ";
		}
		if($_GET['hpId']){
		    $str .= " and id={$_GET['hpId']} ";
		}
		if($_GET['hp_status'])
		{
		    $time = date('Y-m-d H:i:s');
		    switch ($_GET['hp_status'])
		    {
		        case 1://伙拼中
		            $str .= " and status=1 and start_time<'{$time}' and end_time>'{$time}' and ((true_amount+virtual_amount)<low_amount)";break;
		        case 2://伙拼中(已成功)
		            $str .= " and status=1 and start_time<'{$time}' and end_time>'{$time}' and ((true_amount+virtual_amount)>=low_amount)";break;
		        case 3://伙拼结束(已成功)
		            $str .= " and status=1 and end_time<='{$time}' and ((true_amount+virtual_amount)>=low_amount)";break;
		        case 4://伙拼结束(已失败)
		            $str .= " and status=1 and end_time<='{$time}' and ((true_amount+virtual_amount)<low_amount)";break;
		        case 5://配货中
		            $str .= " and status=2 ";break;
		        case 6://已完成
		            $str .= " and status=3 ";break;
		        case 7://已关闭
		            $str .= " and status<=0 ";break;
	            case 8://未开始
	                $str .= " and status=1 and start_time>'{$time}'";break;
		        default:
		            break;
		    }
		}
		
		if($_GET['status']){
		    if($_GET['status']==4){
		        $str .= " and status<=0 ";
		    }else{
		        $str .= " and status={$_GET['status']}";
		    }
		}
		
		if($_GET['stime'])
		{
		    $str.=" and IFNULL(start_time,0) > '".$_GET[stime]."' ";
		}
		if($_GET['etime'])
		{
		    $str.=" and IFNULL(end_time,0) < '".$_GET[etime]."' ";
		}
		
		//获取
		$sql="select * from ".QUANFAN." where status>-9 {$str} order by displayorder asc , id desc ";
		//=============================
		$page = new Page;
		$page->listRows=20;
		if (!$page->__get('totalRows')){
			$db->query($sql);
			$page->totalRows = $db->num_rows();
		}
		$sql .= "  limit ".$page->firstRow.",20";
		$pages = $page->prompt();
		//=====================
		$db->query($sql);
		$de['list']=$db->getRows();
		$de['page']=$page->prompt();
		
		foreach ($de['list'] as $k=>$v)
		{
		    $hpStatusStr = "";
		    switch ($v['status'])
		    {
		        case -9:
		            $hpStatusStr = "已删除";break;
	            case 0:
	                $hpStatusStr = "已关闭";break;
                case 1:
//                     if(strtotime($v['start_time'])<time() && strtotime($v['end_time'])>time()){
//                         $hpStatusStr = "伙拼中";
//                         if((($v['true_amount']+$v['virtual_amount'])>=$v['low_amount'])){
//                             $hpStatusStr .= "(已成功)";
//                         }
//                     }elseif(strtotime($v['start_time'])>time()){
//                         $hpStatusStr = "未开始";
//                     }else{
                        $hpStatusStr = "已上架";
//                         if((($v['true_amount']+$v['virtual_amount'])>=$v['low_amount'])){
//                             $hpStatusStr .= "(已成功)";
//                         }else{
//                             $hpStatusStr .= "(已失败)";
//                         }
//                     }
                    break;
                case 2:
                    $hpStatusStr = "配货中";break;
                case 3:
                    $hpStatusStr = "已完成";break;
                default:
                    break;
		    }
		    
		    $de['list'][$k]['hpStatusStr'] = $hpStatusStr;
		}
	}
	
	
	$tpl->assign("de",$de);
	$tpl->assign("config",$config);
	$tpl->display("quanfan.htm");

?>